const mongoose = require('mongoose');
const bcrypt = require('bcryptjs');
require('dotenv').config();

// 连接数据库
const connectDB = async () => {
  try {
    await mongoose.connect(process.env.MONGODB_URI || 'mongodb://localhost:27017/traveller_new', {
      useNewUrlParser: true,
      useUnifiedTopology: true,
    });
    console.log('✅ MongoDB 连接成功');
  } catch (error) {
    console.error('❌ MongoDB 连接失败:', error);
    process.exit(1);
  }
};

// 用户模型
const userSchema = new mongoose.Schema({
  email: {
    type: String,
    required: true,
    unique: true,
    lowercase: true
  },
  password: {
    type: String,
    required: true
  },
  name: {
    type: String,
    required: true
  },
  avatar: {
    type: String,
    default: null
  },
  bio: {
    type: String,
    default: ''
  },
  location: {
    type: String,
    default: ''
  },
  isActive: {
    type: Boolean,
    default: true
  },
  lastLoginAt: {
    type: Date,
    default: null
  }
}, {
  timestamps: true
});

userSchema.pre('save', async function(next) {
  if (!this.isModified('password')) return next();
  const salt = await bcrypt.genSalt(12);
  this.password = await bcrypt.hash(this.password, salt);
  next();
});

userSchema.methods.comparePassword = async function(password) {
  return await bcrypt.compare(password, this.password);
};

const User = mongoose.model('User', userSchema);

// 目的地模型
const destinationSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  nameEn: {
    type: String,
    required: true
  },
  country: {
    type: String,
    required: true
  },
  description: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true
  },
  coordinates: {
    lat: Number,
    lng: Number
  },
  popularLevel: {
    type: Number,
    min: 1,
    max: 5,
    default: 3
  },
  bestSeason: {
    type: String,
    default: '全年'
  },
  tags: [String]
}, {
  timestamps: true
});

const Destination = mongoose.model('Destination', destinationSchema);

// 景点模型
const attractionSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  destination: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Destination',
    required: true
  },
  description: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true
  },
  coordinates: {
    lat: Number,
    lng: Number
  },
  rating: {
    type: Number,
    min: 0,
    max: 5,
    default: 4.0
  },
  price: {
    type: String,
    default: '免费'
  },
  openTime: {
    type: String,
    default: '全天'
  },
  tags: [String]
}, {
  timestamps: true
});

const Attraction = mongoose.model('Attraction', attractionSchema);

// 酒店模型
const hotelSchema = new mongoose.Schema({
  name: {
    type: String,
    required: true
  },
  destination: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Destination',
    required: true
  },
  description: {
    type: String,
    required: true
  },
  image: {
    type: String,
    required: true
  },
  coordinates: {
    lat: Number,
    lng: Number
  },
  rating: {
    type: Number,
    min: 0,
    max: 5,
    default: 4.0
  },
  priceRange: {
    type: String,
    required: true
  },
  facilities: [String],
  starLevel: {
    type: Number,
    min: 1,
    max: 5,
    default: 3
  }
}, {
  timestamps: true
});

const Hotel = mongoose.model('Hotel', hotelSchema);

// 游记模型
const travellogSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true
  },
  author: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'User',
    required: true
  },
  destination: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'Destination',
    required: true
  },
  content: {
    type: String,
    required: true
  },
  images: [String],
  coverImage: {
    type: String,
    required: true
  },
  tags: [String],
  likes: {
    type: Number,
    default: 0
  },
  views: {
    type: Number,
    default: 0
  },
  isPublished: {
    type: Boolean,
    default: true
  }
}, {
  timestamps: true
});

const Travellog = mongoose.model('Travellog', travellogSchema);

// 初始化数据
const initializeData = async () => {
  try {
    // 删除所有集合以确保干净的启动
    const collections = await mongoose.connection.db.listCollections().toArray();
    for (const collection of collections) {
      await mongoose.connection.db.dropCollection(collection.name);
    }
    
    console.log('🧹 清空所有集合完成');

    // 创建初始用户
    const users = [
      {
        email: 'admin@travel.com',
        password: 'admin123',
        name: '系统管理员',
        bio: '旅游平台管理员',
        location: '北京'
      },
      {
        email: 'user@travel.com',
        password: 'user123',
        name: '旅行爱好者',
        bio: '热爱旅行，分享美好时光',
        location: '上海'
      },
      {
        email: 'test@example.com',
        password: '123456',
        name: '测试用户',
        bio: '这是一个测试账户',
        location: '深圳'
      }
    ];

    // 创建用户（一个个创建以确保密码加密）
    const createdUsers = [];
    for (const userData of users) {
      const user = new User(userData);
      await user.save();
      createdUsers.push(user);
    }
    console.log('👥 用户数据初始化完成');

    // 创建目的地数据
    const destinations = [
      {
        name: '圣托里尼',
        nameEn: 'Santorini',
        country: '希腊',
        description: '爱琴海上的蓝白小镇，拥有世界最美的日落和独特的火山地貌',
        image: '/images/destinations/santorini.jpg',
        coordinates: { lat: 36.3932, lng: 25.4615 },
        popularLevel: 5,
        bestSeason: '4-10月',
        tags: ['海岛', '日落', '蜜月', '摄影']
      },
      {
        name: '雅典',
        nameEn: 'Athens',
        country: '希腊',
        description: '古希腊文明的发源地，拥有众多历史古迹和博物馆',
        image: '/images/destinations/athens.jpg',
        coordinates: { lat: 37.9838, lng: 23.7275 },
        popularLevel: 4,
        bestSeason: '4-6月，9-11月',
        tags: ['历史', '文化', '古迹', '博物馆']
      },
      {
        name: '米克诺斯',
        nameEn: 'Mykonos',
        country: '希腊',
        description: '著名的风车岛，拥有美丽的海滩和活跃的夜生活',
        image: '/images/destinations/mykonos.jpg',
        coordinates: { lat: 37.4467, lng: 25.3289 },
        popularLevel: 4,
        bestSeason: '5-9月',
        tags: ['海岛', '风车', '夜生活', '海滩']
      }
    ];

    const createdDestinations = await Destination.insertMany(destinations);
    console.log('🏝️ 目的地数据初始化完成');

    // 创建景点数据
    const attractions = [
      {
        name: '伊亚小镇',
        destination: createdDestinations[0]._id,
        description: '圣托里尼最著名的小镇，以绝美的日落景色闻名于世',
        image: '/images/attractions/oia.jpg',
        coordinates: { lat: 36.4618, lng: 25.3753 },
        rating: 4.8,
        price: '免费',
        openTime: '全天',
        tags: ['日落', '摄影', '小镇', '必游']
      },
      {
        name: '雅典卫城',
        destination: createdDestinations[1]._id,
        description: '古希腊文明的象征，帕特农神庙等古建筑群的所在地',
        image: '/images/attractions/acropolis.jpg',
        coordinates: { lat: 37.9715, lng: 23.7257 },
        rating: 4.7,
        price: '€20',
        openTime: '8:00-20:00',
        tags: ['历史', '古迹', '必游', '文化']
      },
      {
        name: '米克诺斯风车',
        destination: createdDestinations[2]._id,
        description: '米克诺斯岛的标志性建筑，16世纪建造的传统风车群',
        image: '/images/attractions/windmills.jpg',
        coordinates: { lat: 37.4467, lng: 25.3289 },
        rating: 4.5,
        price: '免费',
        openTime: '全天',
        tags: ['风车', '标志', '摄影', '历史']
      }
    ];

    const createdAttractions = await Attraction.insertMany(attractions);
    console.log('🏛️ 景点数据初始化完成');

    // 创建酒店数据
    const hotels = [
      {
        name: 'Grace Hotel Santorini',
        destination: createdDestinations[0]._id,
        description: '圣托里尼豪华精品酒店，享有爱琴海壮丽景色',
        image: '/images/hotels/grace_santorini.jpg',
        coordinates: { lat: 36.4618, lng: 25.3753 },
        rating: 4.9,
        priceRange: '€800-1200/晚',
        facilities: ['无边泳池', '私人阳台', '海景', 'SPA', '免费WiFi'],
        starLevel: 5
      },
      {
        name: 'Hotel Grande Bretagne',
        destination: createdDestinations[1]._id,
        description: '雅典市中心的经典豪华酒店，毗邻宪法广场',
        image: '/images/hotels/grande_bretagne.jpg',
        coordinates: { lat: 37.9755, lng: 23.7348 },
        rating: 4.6,
        priceRange: '€300-500/晚',
        facilities: ['健身房', '商务中心', '餐厅', '酒吧', '免费WiFi'],
        starLevel: 5
      },
      {
        name: 'Mykonos Grand Hotel',
        destination: createdDestinations[2]._id,
        description: '米克诺斯岛海滨度假酒店，享有爱琴海美景',
        image: '/images/hotels/mykonos_grand.jpg',
        coordinates: { lat: 37.4467, lng: 25.3289 },
        rating: 4.4,
        priceRange: '€400-700/晚',
        facilities: ['私人海滩', '泳池', '水疗', '餐厅', '免费WiFi'],
        starLevel: 4
      }
    ];

    const createdHotels = await Hotel.insertMany(hotels);
    console.log('🏨 酒店数据初始化完成');

    // 创建游记数据
    const travellogs = [
      {
        title: '希腊圣托里尼：蓝白色的浪漫时光',
        author: createdUsers[1]._id,
        destination: createdDestinations[0]._id,
        content: '圣托里尼真的是一个令人难忘的地方。清晨的伊亚小镇安静祥和，蓝色的圆顶教堂在阳光下闪闪发光。最让人印象深刻的是日落时分，整个天空被染成了金红色，配上白色的建筑，简直就是明信片般的美景...',
        images: ['/images/travellogs/santorini1.jpg', '/images/travellogs/santorini2.jpg'],
        coverImage: '/images/travellogs/santorini_cover.jpg',
        tags: ['圣托里尼', '日落', '摄影', '蜜月'],
        likes: 128,
        views: 1520
      },
      {
        title: '雅典一日游：穿越古希腊文明',
        author: createdUsers[1]._id,
        destination: createdDestinations[1]._id,
        content: '雅典是一座充满历史韵味的城市。登上雅典卫城，仿佛穿越到了古希腊时代。帕特农神庙虽然历经沧桑，但依然能感受到它的宏伟壮观。建议早上早点去，可以避开人群，拍到更好的照片...',
        images: ['/images/travellogs/athens1.jpg', '/images/travellogs/athens2.jpg'],
        coverImage: '/images/travellogs/athens_cover.jpg',
        tags: ['雅典', '历史', '古迹', '一日游'],
        likes: 86,
        views: 980
      }
    ];

    const createdTravellogs = await Travellog.insertMany(travellogs);
    console.log('📖 游记数据初始化完成');

    console.log('\n🎉 数据库初始化成功！');
    console.log('📊 数据统计:');
    console.log(`   用户: ${createdUsers.length} 个`);
    console.log(`   目的地: ${createdDestinations.length} 个`);
    console.log(`   景点: ${createdAttractions.length} 个`);
    console.log(`   酒店: ${createdHotels.length} 个`);
    console.log(`   游记: ${createdTravellogs.length} 篇`);

    console.log('\n🔐 测试账户:');
    console.log('   admin@travel.com / admin123 (管理员)');
    console.log('   user@travel.com / user123 (普通用户)');
    console.log('   test@example.com / 123456 (测试用户)');

  } catch (error) {
    console.error('❌ 数据初始化失败:', error);
  }
};

// 运行初始化
const runInit = async () => {
  await connectDB();
  await initializeData();
  mongoose.connection.close();
  console.log('\n👋 数据库连接已关闭');
};

runInit(); 